<template>
  <div>
    <div class="aside-tree-container">
      <div class="projet-head">
        <el-input
          v-model="orgaName"
          placeholder="请输入部门名称 → 回车检索"
          clearable
          size="mini"
          prefix-icon="el-icon-search"
          style="margin-bottom: 12px;width: 240px;margin-left: 20px;margin-right: 10px;"
          @keyup.enter.native="searchProject"
        />
        <el-button type="primary" size="mini" icon="el-icon-search" @click="searchProject">搜索</el-button>
      </div>
      <el-scrollbar style="height: 54vh;">
        <el-tree
          ref="tree"
          v-loading="projectLoading"
          node-key="fid"
          accordion
          :data="deptOptions"
          :props="defaultProps"
          highlight-current
          :expand-on-click-node="false"
          :default-expanded-keys="expandKeys"
          :filter-node-method="filterNodeDept"
          show-checkbox
          :check-strictly="true"
          @check-change="handleCheckChange"
        >
          <div slot-scope="{ node, data }" class="tree-label">
            <svg-icon v-if="data.type === 'dept'" icon-class="ico_area" class="preview-icon" />
            <svg-icon
              v-else-if="data.type === 'project'"
              class="preview-icon"
              style="color: #416ca6;"
              icon-class="druid"
            />
            <span style="padding-left: 6px;padding-right: 10px">{{ node.label }}</span>
            <el-button
              v-if="!node.isLeaf"
              type="text"
              size="mini"
              class="all-select"
              @click="() => selectAll(node, data)"
            >
              {{ node.checked ? '全不选' : '全选' }}
            </el-button>
          </div>
        </el-tree>
      </el-scrollbar>
    </div>
    <div class="footer">
      <el-button type="primary" @click="submitData">确定</el-button>
    </div>
  </div>
</template>

<script>
import { saveUserAuthDept } from '@/api/system/user'
export default {
  name: 'ProjectTree',
  props: {
    type: { // 0: 项目前期名 1：项目后期名称
      type: Number,
      default: () => 0
    },
    deptOptions: {
      type: Array,
      default: () => []
    },
    user: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      orgaName: '',
      projectLoading: false,
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      expandKeys: [],
      t: ''
    }
  },
  watch: {
    // 根据名称筛选部门树
    // orgaName(val) {
    //   this.$refs.tree.filter(val)
    // }
  },
  created() { // 初始化
  },
  methods: {
    // 检索
    searchProject() {
      this.$refs.tree.filter(this.orgaName)
    },
    setCheckedKeys(keys = [], leafOnly = false) {
      this.$refs.tree.setCheckedKeys(keys, leafOnly)
    },
    submitData() {
      const ids = this.$refs.tree.getCheckedKeys()
      const params = {
        dpetFid: ids.join(','),
        userFid: this.user.fid
      }
      saveUserAuthDept(params).then(
        (response) => {
          if (response.code === 200) {
            this.$message.success('组织范围更新成功。')
            this.$emit('success')
          }
        }
      ).finally(() => {

      })
    },
    handleCheckChange(data, checked, indeterminate) {
      // console.log(data, checked, indeterminate)
      this.$emit('check-change', { data, checked, indeterminate })
    },
    invertAll(node, data) { // 当前组织以及子组织反选
      const fids = this.$refs.tree.getCheckedKeys()
      let keys = []
      if (fids.length > 0) {
        keys = [...fids]
        if (keys.some(key => key === data.fid)) {
          keys = keys.filter(key => key !== data.fid)
        } else {
          keys.push(data.fid)
        }
      } else {
        keys.push(data.fid)
      }
      if (data.children && data.children.length) {
        recursion(data.children)
      }
      function recursion(children) {
        if (children && children.length > 0) {
          for (let i = 0; i < children.length; i++) {
            if (keys.some(key => key === children[i].fid)) {
              keys = keys.filter(key => key !== children[i].fid)
            } else {
              keys.push(children[i].fid)
            }
            if (children[i].children && children[i].children.length > 0) {
              recursion(children[i].children)
            }
          }
        }
      }
      this.$refs.tree.setCheckedKeys(keys)
    },
    selectAll(node, data) { // 当前组织以及子组织选中
      const keys = []
      keys.push(data.fid)
      if (data.children && data.children.length) {
        recursion(data.children)
      }
      function recursion(children) {
        if (children && children.length > 0) {
          for (let i = 0; i < children.length; i++) {
            keys.push(children[i].fid)
            if (children[i].children && children[i].children.length > 0) {
              recursion(children[i].children)
            }
          }
        }
      }
      const checked = !node.checked
      for (let j = 0; j < keys.length; j++) {
        this.$refs.tree.setChecked(keys[j], checked)
      }
    },
    // 组织筛选节点
    filterNodeDept(value, data, node) {
      if (!value) return true
      // return data.label.indexOf(value) !== -1
      let parentNode = node.parent
      let labels = [node.label]
      let level = 1
      while (level < node.level) {
        labels = [...labels, parentNode.label]
        parentNode = parentNode.parent
        level++
      }
      return labels.some(label => label && label.indexOf(value) !== -1)
    }
  }
}
</script>

<style scoped lang='scss'>
  .aside-tree-container {
    .projet-head {
      padding-top: 10px;
      border-bottom: 1px solid rgba(0, 0, 0, 0.1);
      margin-bottom: 10px;
    }
    font-size: 12px;
    box-shadow: 0 0 2px 0 rgba(0, 0, 0, 0.2);
    .tree-label {
      width: 100%;
      .all-select {
        display: none;
      }
      &:hover {
      .all-select{
        display: inline-block;
      }
    }
    }
  }
  .footer {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }
</style>
<style lang="scss">
  .check-type-scrollbar-container,
  .aside-tree-container {
    .el-scrollbar .el-scrollbar__wrap {
      overflow-x: hidden;
    }
  }
</style>
